<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '编辑'" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter.native="dataFormSubmitHandle()" label-width="120px">
      <el-form-item prop="menuType" label="类型" >
        <el-radio-group v-model="dataForm.menuType" :disabled="!!dataForm.id">
          <el-radio :label="0">菜单</el-radio>
          <el-radio :label="1">按钮</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="name" label="名称">
        <el-input v-model="dataForm.name" placeholder="名称"></el-input>
      </el-form-item>
      <el-form-item prop="parentName" label="上级菜单" class="menu-list">
        <el-popover v-model:visible="menuListVisible" ref="menuListPopover" placement="bottom-start" trigger="click">
          <el-tree
            :data="menuList"
            :props="{ label: 'name', children: 'children' }"
            node-key="id"
            ref="menuListTreeRef"
            :highlight-current="true"
            :expand-on-click-node="false"
            accordion
            @current-change="menuListTreeCurrentChangeHandle">
          </el-tree>
	        <template #reference>
		        <el-input v-model="dataForm.parentName" :readonly="true" placeholder="上级菜单">
			        <template #suffix>
				        <i v-if="dataForm.pid !== '0'" @click.stop="deptListTreeSetDefaultHandle()" class="el-icon-circle-close el-input__icon"></i>
			        </template>
		        </el-input>
	        </template>
        </el-popover>
      </el-form-item>
      <el-form-item v-if="dataForm.menuType === 0" prop="url" label="路由">
        <el-input v-model="dataForm.url" placeholder="路由"></el-input>
      </el-form-item>
      <el-form-item prop="sort" label="排序">
        <el-input-number v-model="dataForm.sort" controls-position="right" :min="0" label="排序"></el-input-number>
      </el-form-item>
      <el-form-item prop="permissions" label="授权标识">
        <el-input v-model="dataForm.permissions" placeholder="多个用逗号分隔，如：sys:menu:save,sys:menu:update"></el-input>
      </el-form-item>
      <el-form-item v-if="dataForm.menuType === 0" prop="icon" label="图标" class="icon-list">
        <el-popover width="460px" v-model="iconListVisible" ref="iconListPopover" placement="bottom-start" trigger="click" popper-class="mod-sys__menu-icon-popover">
          <div class="mod-sys__menu-icon-inner">
            <div class="mod-sys__menu-icon-list">
              <el-button
                v-for="(item, index) in iconList"
                :key="index"
                @click="iconListCurrentChangeHandle(item)"
                :class="{ 'is-active': dataForm.icon === item }">
                <svg class="icon-svg" aria-hidden="true"><use :xlink:href="`#${item}`"></use></svg>
              </el-button>
            </div>
          </div>
	        <template #reference>
		        <el-input v-model="dataForm.icon" :readonly="true" placeholder="图标"></el-input>
	        </template>
        </el-popover>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import debounce from 'lodash/debounce'
import {getIconList} from "../../../utils/util.js";
import {computed, nextTick, reactive, ref, watch} from "vue";

import http from "../../../utils/request.js";
import {message} from "../../../utils/commonScript.js";

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const menuList = ref([])
const menuListVisible = ref(false)
const iconList = ref([])
const iconListVisible = ref(false)
const dataForm = reactive({
	id: '',
	menuType: 0,
	name: '',
	pid: '0',
	parentName: '',
	url: '',
	permissions: '',
	sort: 0,
	icon: ''
})
const dataFormRef = ref()
const menuListTreeRef = ref()

const dataRule = computed(() => {
	return {
		name: [
			{ required: true, message: '必填项不能为空', trigger: 'blur' }
		],
		parentName: [
			{ required: true, message: '必填项不能为空', trigger: 'change' }
		]
	}
})

const init = (id='') => {
	visible.value = true
	dataForm.id = id
	nextTick(() => {
		dataFormRef.value.resetFields()
		iconList.value = getIconList()
		dataForm.parentName = '一级菜单'
		getMenuList().then(() => {
			if (dataForm.id) {
				getInfo()
			}
		})
	})
}
// 获取菜单列表
const getMenuList = () => {
	return http.get('/sys/menu/list?type=0').then(({ data: res }) => {
		if (res.code !== 0) {
			return message.error(res.msg)
		}
		menuList.value = res.data
	}).catch(() => {})
}
// 获取信息
const getInfo = () => {
	http.get(`/sys/menu/${dataForm.id}`).then(({ data: res }) => {
		if (res.code !== 0) {
			return message.error(res.msg)
		}
		dataForm.menuType = res.data.menuType
		dataForm.name = res.data.name
		dataForm.pid = res.data.pid
		dataForm.parentName = res.data.parentName
		dataForm.url = res.data.url
		dataForm.permissions = res.data.permissions
		dataForm.sort = res.data.sort
		dataForm.icon = res.data.icon
		if (dataForm.pid === '0') {
			return deptListTreeSetDefaultHandle()
		}
		menuListTreeRef.value.setCurrentKey(dataForm.pid)
	}).catch(() => {})
}
// 上级菜单树, 设置默认值
const deptListTreeSetDefaultHandle = () => {
	dataForm.pid = '0'
	dataForm.parentName = '一级菜单'
}
// 上级菜单树, 选中
const menuListTreeCurrentChangeHandle = (data) => {
	dataForm.pid = data.id
	dataForm.parentName = data.name
	menuListVisible.value = false
}
// 图标, 选中
const iconListCurrentChangeHandle = (icon) => {
	dataForm.icon = icon
	iconListVisible.value = false
}
// 表单提交
const dataFormSubmitHandle = debounce(function () {
	dataFormRef.value.validate((valid) => {
		if (!valid) {
			return false
		}
		http[!dataForm.id ? 'post' : 'put']('/sys/menu', dataForm).then(({ data: res }) => {
			if (res.code !== 0) {
				return message.error(res.msg)
			}
			message({
				message: '操作成功',
				type: 'success',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		}).catch(() => {})
	})
}, 1000, { 'leading': true, 'trailing': false })

watch(()=>dataForm.menuType, (val) => {
	dataFormRef.value.clearValidate()
})

defineExpose({
	init
})
</script>

<style lang="scss">
.mod-sys__menu {
  .menu-list,
  .icon-list {
    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }
  &-icon-popover {
    width: 458px;
    overflow: hidden;
  }
  &-icon-inner {
    width: 478px;
    max-height: 258px;
    overflow-x: hidden;
    overflow-y: auto;
  }
  &-icon-list {
    width: 458px;
    padding: 0;
    margin: -8px 0 0 -8px;
    > .el-button {
      padding: 8px;
      margin: 8px 0 0 8px;
      > span {
        display: inline-block;
        vertical-align: middle;
        width: 18px;
        height: 18px;
        font-size: 18px;
      }
    }
  }
}
</style>
